/**
 * The standard Java Tokenizer class is not available in J2ME or CLDC 1.1
 * so this class implements the methods needed to recreate an agent from
 * a string once received.
 * 
 * @author Aidan
 */
package ap;

public class Tokenizer {
	private String str;
	private String delim;
	private int i,j, delimLength;
	private boolean found;
		
	public Tokenizer(String str, String delim){
		this.delim = delim;
		this.str = str;
		j = 0;
		delimLength = delim.length();
	}
	
	public Tokenizer(String str, char delim){
		this.delim = "" + delim;
		this.str = str;
		j = 0;
		delimLength = 1;
	}
	/****************************************************************
	 * Allow Tokenizer to be reset
	 * @param str
	 * @param delim
	 */
	public void resetTokenizer(String str, String delim){
		this.delim = delim;
		this.str = str;
		j = 0;
		delimLength = delim.length();
	}
	/**
	 * Allow Tokenizer to be reset
	 * @param str
	 * @param delim
	 */
	public void resetTokenizer(String str, char delim){
		this.delim = "" + delim;
		this.str = str;
		j = 0;
		delimLength = 1;
	}
	
	/**
	 * Allow delim to be reset
	 * @param str
	 * @param delim
	 */
	public void setDelim(String str, String delim){
		this.delim = delim;
		delimLength = delim.length();
	}
	/**
	 * Allow delim to be reset
	 * @param str
	 * @param delim
	 */
	public void setDelim(String str, char delim){
		this.delim = "" + delim;
		delimLength = 1;
	}
	
	/****************************************************************
	 * j holds the place in the string to start looking from.
	 * i is assigned the place of j, and j scans through the string
	 * until it finds a matching delim. 
	 * @return substring from i - delim
	 **/
	public String nextToken() throws NoSuchElementException{
		String token = new String();
		i = j;
		found = false;
		while( j <= str.length()-delimLength && !found){
			if( str.substring( j, j+delimLength).equals(delim) ){
				token = str.substring( i, j );
				found = true;
			}
			else
				j++;
		}
		j += delimLength;
		
		if( !found ){
			throw new NoSuchElementException("Agent Array Empty");
		}
		else
			return token;
	}
	/****************************************************************
	 * j holds the place in the string to start looking from.
	 * k is assigned the place of j, and k scans through the string
	 * until it finds a matching delim or reaches the end of the string
	 * 
	 * @return true if hasMoreTokens
	 * @return false if not
	 **/
	public boolean hasMoreTokens(){
		int k = j;
		found = false;
		while( k <= str.length()-delimLength && !found){
			if( str.substring( k, k+delimLength).equals(delim) ){
				found = true;
			}
			else
				k++;
		}
		
		return found;		 
	 }
}
